package cn.zhentao;

import cn.zhentao.util.JwtService;
import cn.zhentao.util.Result;
import cn.zhentao.util.ThreadLocalUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@WebFilter("/*")
public class Filter implements javax.servlet.Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String url = request.getRequestURI();
        if(url.equals("/user/login") || url.equals("/user/onRepeatPhone") || url.equals("/user/onRepeatUserName") || url.equals("/user/register") || url.equals("/user/forgotPassword") || url.equals("/user/phone") || url.equals("/user/phonelogin") || url.equals("/delivery/task-package") || url.equals("/delivery/read") || url.equals("/delivery/readAll") || url.startsWith("/images") || url.startsWith("/delivery/collect")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        String token = request.getHeader("Authorization");
        if(JwtService.verifyToken(token)==1){
            ThreadLocalUtil.set(token);
            filterChain.doFilter(servletRequest,servletResponse);
        }else {
            response.setContentType("application/json;charset=utf-8");
            Result error = Result.ERROR();
            error.setMessage("token错误");
            response.getWriter().write(JSON.toJSONString(error));
        }
    }
}
